package hk.polyu.dds;

import java.io.*;
import java.net.*;

import android.os.Handler;
import android.util.Log;


public class DataClient extends Thread {
	
	private InetAddress			mServerAddr = null;
	
	// Client data structure
	private Socket				mClientSocket = null;
	private BufferedWriter		mOut = null;
	private BufferedReader		mIn = null;
	private String 				mLocalName = null;
	private Handler 			mHandler;
	private boolean				mIsRunning = true;
	
	public static long			mTimeDiff = 0;
	
	public DataClient(Handler h, InetAddress serverAddr) {
		mServerAddr = serverAddr;
		mHandler = h;
	}
	
	public void stopClient() {
		this.mIsRunning = false;
		
	}
	
	
	@Override
	public void run() {
    	
		// get server Info.
		InetSocketAddress addr = new InetSocketAddress(mServerAddr, 9988);
		
		mClientSocket = new Socket();
    	
    	try {
			mClientSocket.bind(null);
	    	mClientSocket.connect(addr, 5000);
	    	
	    	// get local name
	    	this.mLocalName = mClientSocket.getLocalAddress().getHostName();
	    	
	    	mOut = new BufferedWriter(new OutputStreamWriter(mClientSocket.getOutputStream()));
	    	mIn = new BufferedReader(new InputStreamReader(mClientSocket.getInputStream()));
	    	// send initial handshake.
	    	String sent = "CONN " + mLocalName + "\r\n";
	    	mOut.write(sent);
	    	Log.d("polyu", "Client Send : " + sent);
	    	mOut.flush();
	    
	    	String line = mIn.readLine();	
	    	Log.d("polyu", "Client received : " + line);
	    	
	    	String [] parts = line.split(" ");
	    	
	    	if (! parts[0].equalsIgnoreCase("OKOK"))
	    		throw new Exception("Handshake failed");
	    	
	    	// interpret the content, get server timestamp and store.
	    	long serverTime = Long.parseLong(parts[1]);
	    	DataClient.mTimeDiff = System.currentTimeMillis() - serverTime;
	    	// DONE, wating for the start command.
	    	
	    	while( mIsRunning == true) {
	    	
		    	line = mIn.readLine();
		    	Log.d("polyu", "Client received : " + line);
		    	
		    	if( line == null)
		    		continue;
		    	
		    	parts = line.split(" ");
		    	
		    	if (parts[0].equalsIgnoreCase("BEGN")) {
		    		serverTime = Long.parseLong(parts[1]);
			    	DataClient.mTimeDiff = System.currentTimeMillis() - serverTime;
		    		this.mHandler.sendEmptyMessage(MainUI.MSG_STARTSAMPLE);
		    	}
		    	else if (parts[0].equalsIgnoreCase("ENDS")) {
		    		this.mHandler.sendEmptyMessage(MainUI.MSG_STOPSAMPLE);
		    	}
	    	}
	    	
	    	this.mOut.close();
	    	this.mIn.close();
	    	this.mClientSocket.close();
	    	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
